package cn.itcast.hotel.listen;

import cn.itcast.hotel.config.MqConstants;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description: 监听 MQ 队列消息,同步索引库
 * @Version: V1.0
 */
@Component
@Slf4j
public class IndexListener {

    @Autowired
    IHotelService hotelService;

    @RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)
    public void insertListen(String message) {
        log.info("IndexListener insertListen sync start param:{}", message);
        try {

            if (StringUtils.isNotBlank(message)) {
                Map<String,String> map = JSON.parseObject(message, Map.class);
                hotelService.insertById(Long.valueOf(map.get("hotelId")));
            }


        } catch (Exception e) {
            e.printStackTrace();
            // 记录并通知给相关人员
            log.error("IndexListener sync error,ex: {}, param:{}", e.getMessage(), message);
        }
        log.info("IndexListener insertListen sync success");
    }

    @RabbitListener(queues = MqConstants.HOTEL_DELETE_QUEUE)
    public void deleteListen(String message) {
        if (StringUtils.isNotBlank(message)) {
            Map<String,String> map = JSON.parseObject(message, Map.class);
            hotelService.deleteById(Long.valueOf(map.get("hotelId")));

        }
    }
}
